#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import List, Dict, Any, Optional, Literal
from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, Query, Path
from fastapi.responses import JSONResponse

from app.core.dependencies import get_services
from app.core.exceptions import NotFoundError, DatabaseError
from app.models.api import (
    QueryHistoryResponse,
    QueryHistoryFilter,
    PaginatedResponse
)

# 创建路由
router = APIRouter()


@router.get("/{project_id}/history", response_model=PaginatedResponse)
async def list_query_history(
    project_id: str = Path(..., description="项目ID"),
    type: Optional[Literal["generation", "correction"]] = Query(None, description="历史类型"),
    start_date: Optional[datetime] = Query(None, description="开始日期"),
    end_date: Optional[datetime] = Query(None, description="结束日期"),
    db_type: Optional[str] = Query(None, description="数据库类型"),
    limit: int = Query(10, ge=1, le=100),
    offset: int = Query(0, ge=0),
    services=Depends(get_services)
):
    """列出查询历史"""
    try:
        # 检查项目是否存在
        await services["project_service"].get_project(project_id)
        
        # 获取查询历史
        history_list, total = await services["query_history_service"].list_history(
            project_id=project_id,
            history_type=type,
            start_date=start_date,
            end_date=end_date,
            db_type=db_type,
            limit=limit,
            offset=offset
        )
        
        # 转换为响应模型
        items = [QueryHistoryResponse.model_validate(history) for history in history_list]
        
        return {
            "items": items,
            "total": total,
            "limit": limit,
            "offset": offset
        }
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{project_id}/history/{history_id}", response_model=QueryHistoryResponse)
async def get_query_history(
    project_id: str = Path(..., description="项目ID"),
    history_id: int = Path(..., description="历史ID"),
    services=Depends(get_services)
):
    """获取查询历史"""
    try:
        # 获取查询历史
        history = await services["query_history_service"].get_history(history_id)
        
        # 检查项目ID是否匹配
        if history.project_id != project_id:
            raise HTTPException(status_code=404, detail="查询历史不存在或不属于指定项目")
        
        return QueryHistoryResponse.model_validate(history)
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except DatabaseError as e:
        raise HTTPException(status_code=500, detail=str(e))